from flask import Flask, request
from flask_cors import CORS
from dataUtil import mongoConnect, sparkConnect
import json
import time


app = Flask(__name__)
CORS(app, resources={r'/*'}, supports_credentials=True)


@app.route("/get_labels", methods=["POST", "GET"])
def get_labels_by_name():
    data = request.args.get("label_name")
    results = mongoConnect.get_labels_by_name(data)
    return json.dumps(results, ensure_ascii=False)


@app.route("/addlabel", methods=["POST", "GET"])
def add_label():
    # return "sucess"
    data = request.data
    data = json.loads(data)
    data['conditions'] = json.loads(data['conditions'])
    cur_time = time.time()
    cur_hash = hash(str(cur_time) + str(data))
    data['id'] = str(cur_hash % 10000)
    # mongo insert
    sparkConnect.add_tag_to_item(data['topic'], data)
    mongoConnect.insert_a_label(data)
    return "success"


@app.route("/get_label", methods=["POST", "GET"])
def get_label():
    data = request.get_json()
    label_id = data['label_id']
    return mongoConnect.get_a_label(label_id)


@app.route("/delete_label", methods=["POST", "GET"])
def del_label():
    label_id = request.args.get("label_id")
    print(label_id)
    return mongoConnect.del_a_label(label_id)


@app.route("/get_tags", methods=["POST", "GET"])
def get_tags_by_topic():
    data = request.args.get("topic")
    print(data)
    result = mongoConnect.get_labels_by_topic(data)
    print(result)
    results = []
    for i in result['results']:
        results.append({
            'label': i['name'],
            'value': i['id']
        })
    return json.dumps(results, ensure_ascii=False)


if __name__ == "__main__":
    import setproctitle
    setproctitle.setproctitle("bdmo-label")
    app.debug = True
    app.run(host='0.0.0.0', port=5002)
